<template>
  <div class="pie-chart-container">
    <!-- 头部标题 -->
    <h3 class="chart-title">资源统计</h3>

    <!-- 图表容器 -->
    <div class="chart-wrapper">
      <div ref="chartRef" style="width: 300px; height: 200px;"></div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onUnmounted } from 'vue';
// 引入API
import { getPieChartData } from '@/api/dashboard';

const chartRef = ref(null);
let myChart = null;

const initChart = async (pieData) => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);

    const option = {
      tooltip: {
        trigger: 'item'
      },
      // 将图例设置在右侧
      legend: {
        orient: 'vertical',  // 垂直排列
        left: 'right',       // 放置在右侧
        top: 'center',       // 垂直居中对齐
        itemGap: 15,         // 图例项之间的距离
        textStyle: {
          fontSize: 12       // 调整图例文字大小
        }
      },
      series: [
        {
          name: '资源统计',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: pieData
        }
      ]
    };

    myChart.setOption(option);

    // 监听窗口大小变化，自适应调整图表
    const handleResize = () => {
      myChart.resize();
    };
    window.addEventListener('resize', handleResize);

    // 组件卸载时移除事件监听
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
    });
  }
};

onMounted(async () => {
  // 从后端获取饼图数据
  try {
    const response = await getPieChartData();
    if (response.code === 200) {
      initChart(response.data);
    } else {
      // 如果获取数据失败，显示空图表
      initChart([]);
    }
  } catch (error) {
    console.error('获取饼图数据失败:', error);
    // 如果获取数据失败，显示空图表
    initChart([]);
  }
});

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style scoped lang="scss">
.pie-chart-container {
  width: 100%;
  max-width: 600px; /* 限制最大宽度 */
  padding: 10px;
}

.chart-title {
  margin: 0 0 15px 0;
  padding: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  text-align: left; /* 标题左对齐 */
}

.chart-wrapper {
  width: 100%;
  position: relative;
}
</style>
